// 文科生学编程 - 主JavaScript文件

// 全局变量
let currentLevel = 0;
let completedLevels = [];
let userCode = '';

// 关卡数据
const levels = {
    1: {
        title: "什么是代码？",
        concept: `
            <h4 class="text-lg font-semibold mb-2">代码就像写给计算机的情书</h4>
            <p class="mb-4">想象你有一个机器人朋友，它非常聪明但有点"死板"。</p>
            <p class="mb-4">代码就是你写给它的指令，告诉它：</p>
            <ul class="list-disc list-inside mb-4">
                <li>先做什么（比如：说"你好"）</li>
                <li>然后做什么（比如：问对方名字）</li>
                <li>如果...就...（如果对方说"小明"，就说"很高兴认识你"）</li>
            </ul>
            <p>就像写诗一样，每一行都有它的韵律和意义！</p>
        `,
        blocks: [
            { id: 'print', text: '说"你好，世界！"', code: 'print("你好，世界！")' },
            { id: 'name', text: '问对方名字', code: 'name = input("你叫什么名字？")' }
        ],
        expectedOutput: "你好，世界！"
    },
    2: {
        title: "变量魔法",
        concept: `
            <h4 class="text-lg font-semibold mb-2">变量就是给数据起名字</h4>
            <p class="mb-4">想象你有一个魔法盒子，可以给任何东西贴上标签。</p>
            <p class="mb-4">在编程中，我们这样给数据起名字：</p>
            <ul class="list-disc list-inside mb-4">
                <li><code>年龄 = 18</code> - 把数字18贴上"年龄"的标签</li>
                <li><code>名字 = "小明"</code> - 把文字"小明"贴上"名字"的标签</li>
                <li>以后只要说"年龄"，计算机就知道是18</li>
            </ul>
            <p>就像给宠物取名一样简单！</p>
        `,
        blocks: [
            { id: 'var1', text: '年龄 = 18', code: 'age = 18' },
            { id: 'var2', text: '名字 = "小明"', code: 'name = "小明"' },
            { id: 'print2', text: '打印自我介绍', code: 'print(f"大家好，我是{name}，今年{age}岁")' }
        ],
        expectedOutput: "大家好，我是小明，今年18岁"
    },
    3: {
        title: "条件判断",
        concept: `
            <h4 class="text-lg font-semibold mb-2">如果...那么...就像人生的选择题</h4>
            <p class="mb-4">想象你在写一首诗：</p>
            <ul class="list-disc list-inside mb-4">
                <li>如果今天下雨，我就带伞</li>
                <li>如果看到彩虹，我就拍照</li>
                <li>如果心情不好，我就吃巧克力</li>
            </ul>
            <p>编程中的条件判断就是这样：</p>
            <pre class="code-highlight mt-4"><code><span class="keyword">if</span> <span class="string">天气</span> == <span class="string">"下雨"</span>:
    <span class="keyword">print</span>(<span class="string">"记得带伞！"</span>)</code></pre>
        `,
        blocks: [
            { id: 'if1', text: '如果天气好', code: 'weather = "晴天"' },
            { id: 'if2', text: '打印出去玩', code: 'if weather == "晴天":\n    print("今天天气真好，出去玩吧！")' },
            { id: 'else', text: '否则打印在家', code: 'else:\n    print("今天在家看书吧")' }
        ],
        expectedOutput: "今天天气真好，出去玩吧！"
    }
};

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    loadProgress();
    updateUI();
});

// 开始旅程
function startJourney() {
    document.querySelector('.hero').classList.add('hidden');
    document.getElementById('map-section').classList.remove('hidden');
}

// 打开关卡
function openLevel(levelNum) {
    currentLevel = levelNum;
    const level = levels[levelNum];
    
    // 更新概念解释
    document.getElementById('concept-title').textContent = level.title;
    document.getElementById('concept-content').innerHTML = level.concept;
    
    // 更新积木块
    updateBlocksPalette(level.blocks);
    
    // 清空代码区域
    document.getElementById('code-display').textContent = '';
    document.getElementById('result-display').classList.add('hidden');
    
    // 显示学习区域
    document.getElementById('map-section').classList.add('hidden');
    document.getElementById('learning-section').classList.remove('hidden');
}

// 更新积木块调色板
function updateBlocksPalette(blocks) {
    const palette = document.getElementById('blocks-palette');
    palette.innerHTML = '';
    
    blocks.forEach(block => {
        const blockEl = document.createElement('div');
        blockEl.className = 'code-block';
        blockEl.textContent = block.text;
        blockEl.draggable = true;
        blockEl.dataset.code = block.code;
        
        blockEl.addEventListener('dragstart', handleDragStart);
        blockEl.addEventListener('click', () => addCodeBlock(block.code));
        
        palette.appendChild(blockEl);
    });
}

// 拖拽开始
function handleDragStart(e) {
    e.dataTransfer.setData('text/plain', e.target.dataset.code);
}

// 添加代码块
function addCodeBlock(code) {
    const display = document.getElementById('code-display');
    if (display.textContent) {
        display.textContent += '\n' + code;
    } else {
        display.textContent = code;
    }
    userCode = display.textContent;
}

// 运行代码
function runCode() {
    const code = document.getElementById('code-display').textContent;
    const output = document.getElementById('output');
    const resultDisplay = document.getElementById('result-display');
    
    try {
        // 模拟运行Python代码
        let result = '';
        
        // 简单的代码执行模拟
        if (code.includes('print("你好，世界！")')) {
            result = '你好，世界！';
        } else if (code.includes('print(f"大家好，我是{name}，今年{age}岁")')) {
            result = '大家好，我是小明，今年18岁';
        } else if (code.includes('print("今天天气真好，出去玩吧！")')) {
            result = '今天天气真好，出去玩吧！';
        }
        
        output.innerHTML = `<p class="text-green-600 font-semibold">${result}</p>`;
        resultDisplay.classList.remove('hidden');
        
        // 检查是否完成关卡
        checkLevelCompletion(result);
        
    } catch (error) {
        output.innerHTML = `<p class="text-red-600">出错了：${error.message}</p>`;
        resultDisplay.classList.remove('hidden');
    }
}

// 检查关卡完成
function checkLevelCompletion(result) {
    const expected = levels[currentLevel].expectedOutput;
    if (result === expected) {
        if (!completedLevels.includes(currentLevel)) {
            completedLevels.push(currentLevel);
            saveProgress();
            showAchievement(levels[currentLevel].title);
            updateProgress();
        }
    }
}

// 显示成就
function showAchievement(achievementName) {
    document.getElementById('achievement-name').textContent = achievementName;
    document.getElementById('achievement-modal').showModal();
}

// 返回地图
function backToMap() {
    document.getElementById('learning-section').classList.add('hidden');
    document.getElementById('map-section').classList.remove('hidden');
}

// 保存进度
function saveProgress() {
    localStorage.setItem('programmingProgress', JSON.stringify(completedLevels));
}

// 加载进度
function loadProgress() {
    const saved = localStorage.getItem('programmingProgress');
    if (saved) {
        completedLevels = JSON.parse(saved);
    }
}

// 更新UI
function updateUI() {
    // 更新关卡状态
    completedLevels.forEach(level => {
        const button = document.querySelector(`[onclick="openLevel(${level})"]`);
        if (button) {
            button.classList.add('btn-success');
            button.innerHTML = '<i class="fas fa-check mr-2"></i>已完成';
        }
    });
}

// 更新进度
function updateProgress() {
    const totalLevels = Object.keys(levels).length;
    const completed = completedLevels.length;
    const percentage = (completed / totalLevels) * 100;
    
    // 这里可以更新进度条
    console.log(`进度：${completed}/${totalLevels} (${percentage.toFixed(0)}%)`);
}

// 一键生成作品
function generateProject() {
    if (completedLevels.length === 0) {
        alert('先完成至少一个关卡才能生成作品哦！');
        return;
    }
    
    const projectCode = `
<!DOCTYPE html>
<html>
<head>
    <title>我的第一个程序</title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            text-align: center; 
            padding: 50px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
    </style>
</head>
<body>
    <h1>我的编程之旅开始了！</h1>
    <p>我已经完成了 ${completedLevels.length} 个关卡</p>
    <p>代码让世界变得更美好</p>
</body>
</html>`;
    
    // 创建下载链接
    const blob = new Blob([projectCode], { type: 'text/html' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = '我的第一个程序.html';
    a.click();
    
    URL.revokeObjectURL(url);
}

// 添加全局函数到window对象
window.startJourney = startJourney;
window.openLevel = openLevel;
window.runCode = runCode;
window.backToMap = backToMap;
window.generateProject = generateProject;
